﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="AutoPopulateExportedViewsBehavior.cs" company="http://buginbox.wordpress.com/">
//   Copyright (c) GNU General Public License version 2 (GPLv2)
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

using System;
using System.ComponentModel.Composition;
using Microsoft.Practices.Prism.Regions;

namespace Wpf.Core.Behavior
{
    /// <summary>
    /// Default behavior for PRISM regions : controls declared in a region are auto added
    /// </summary>
    [Export(typeof(AutoPopulateExportedViewsBehavior))]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class AutoPopulateExportedViewsBehavior : RegionBehavior, IPartImportsSatisfiedNotification
    {
        /// <summary>
        /// The on attach.
        /// </summary>
        protected override void OnAttach()
        {
            AddRegisteredViews();
        }

        /// <summary>
        /// The on imports satisfied.
        /// </summary>
        public void OnImportsSatisfied()
        {
            AddRegisteredViews();
        }

        /// <summary>
        /// The add registered views.
        /// </summary>
        private void AddRegisteredViews()
        {
            if (Region != null)
            {
                foreach (var viewEntry in RegisteredViews)
                {
                    if (viewEntry.Metadata.RegionName == Region.Name)
                    {
                        var view = viewEntry.Value;

                        if (!Region.Views.Contains(view))
                        {
                            Region.Add(view);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Gets or sets RegisteredViews.
        /// </summary>
        [ImportMany(AllowRecomposition = true)]
        public Lazy<object, IViewRegionRegistration>[] RegisteredViews
        {
            get;
            set;
        }
    }
}